﻿@page "/MessageDefine"

@namespace SageKing.Studio.Pages.SageKingMessage

@implements IMenuTab<SysMenu, long>
@implements IReuseTabsPage

@inject IMessageService _message
@inject IConfirmService _confirmService
@inject SysDictTypeService selectService

@inject SysMenuService _sysMenuService
@inject SysSageKingMessageService dataService
@inject SysSageKingMessageInstanceService dataInstanceService
@inject SysSageKingMessageAttributeService dataDetailService

@using SageKing.Studio.Pages.SageKingMessage.component

<PageTitle>@TabTitle</PageTitle>

@if (pageData == null)
{
	<Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
	<Table @ref="table" TItem="SysSageKingMessage" Class="main-table" ScrollY="@BrowserConsts.ScrollYTable"
		   DataSource="@pageData.Items"
		   RowKey="x=>x.Id"
		   OnRowClick="OnRowClick"
		   @bind-SelectedRows="@selectedRows"
		   Size="TableSize.Small"
		   OnChange="OnChange"
		   OnExpand="OnRowExpand" Loading="tableLoading"
		   Resizable Bordered EnableVirtualization
		   PageSize="pageData.PageSize">
		<TitleTemplate>
			<Space>
				<SpaceItem>
					<Select @bind-Value="@searchModel.Type"
							DataSource="@SelectSearchModelType.Children"
							LabelName="@nameof(SysDictData.CodeValue)"
							ValueName="@nameof(SysDictData.ValueInt)"
							Style="min-width:150px; width: auto;"
							TItemValue="int"
							TItem="SysDictData"
							Placeholder="请选消息类型"
							AllowClear
							EnableSearch>
					</Select>
				</SpaceItem>
				<SpaceItem>
					<Search Placeholder="消息名称" @bind-Value="searchModel.Name" OnSearch="async ()=>{await OnSearch(pageargs);Message(); }" AllowClear="true" />
				</SpaceItem>

				<SpaceItem>
					<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Reload" OnClick="()=>SearchModelReSet()">重置</Button>
				</SpaceItem>

				<SpaceItem>
					<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.AppstoreAdd" OnClick="()=>skMessageMainFrmModal.MeCrud.ShowAdd(0)">新增</Button>
				</SpaceItem>

				<SpaceItem>
					<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Import" OnClick="(e)=>skImportFrmDBModal.MeCrud.ShowAdd(0)">快速导入(数据库)</Button>
				</SpaceItem>
			</Space>
		</TitleTemplate>
		<ColumnDefinitions>
			<Selection Type="@selectionType"></Selection>
			<PropertyColumn Property="c=>c.Name" Title="消息名称" Sortable="true" Filterable />
			<PropertyColumn Property="c=>c.Type" Title="类型" Sortable="true" Align="ColumnAlign.Center" Filterable>
				<Text>@GetTypeDesc(context.Type)</Text>
			</PropertyColumn>
			<PropertyColumn Property="c=>c.Status" Title="状态" Align="ColumnAlign.Center" Sortable="true" Filterable>
				<Switch @bind-Value="@context.Status" OnClick="()=>skMessageMainFrmModal.EditOnStatusSwitch(context)" CheckedChildren="开" UnCheckedChildren="关"></Switch>
			</PropertyColumn>
			<PropertyColumn Property="c=>c.Description" Title="描述信息" Ellipsis />
			<PropertyColumn Property="c=>c.Version" Title="Version" Sortable="true" Filterable></PropertyColumn>
			<PropertyColumn Property="c=>c.Id" Title="Id" Sortable="true" Filterable />
			<PropertyColumn Title="时间相关" Property="c=>c.CreateUserName" Align="ColumnAlign.Center">
				<Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
					<Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
				</Popover>
			</PropertyColumn>
			<ActionColumn Title="消息操作" Align="ColumnAlign.Center">
				<Space>
					<SpaceItem>
						<Tooltip Title="发送，客户端向服务端发送消息。">
							<Button OnClick="(e)=>skMessageFrmToSendModal.ShowSendData(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Send" />
						</Tooltip>
					</SpaceItem>
					<SpaceItem>
						<Tooltip Title="推送，服务端向客户端推送消息。">
							<Button OnClick="(e)=>skMessageFrmToSendModal.ShowPushData(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Notification" />
						</Tooltip>
					</SpaceItem>
					<SpaceItem>
						<Tooltip Title="生成C# Entity代码">
							<Button OnClick="async (e)=>await codeEditBoxModal.MeCrud.ShowAdd(context,false)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Code" />
						</Tooltip>
					</SpaceItem>
				</Space>
			</ActionColumn>
			<ActionColumn Title="Action" Fixed="ColumnFixPlacement.Right">
				<Space>
					<SpaceItem>
						<Tooltip Title="@IconType.Outline.Edit">
							<Button OnClick="(e)=>skMessageMainFrmModal.MeCrud.ShowEdit(context)" Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Edit" />
						</Tooltip>
					</SpaceItem>
					<SpaceItem>
						<Popconfirm Title="删除当前记录?"
									OnConfirm="(e) => skMessageMainFrmModal.DeleteData(context,null)"
									OkText="Yes"
									CancelText="No">
							<Button Icon="@IconType.Outline.Delete" Shape="@ButtonShape.Circle" Danger></Button>
						</Popconfirm>
					</SpaceItem>
					<SpaceItem>
						<Popconfirm Title="清理生成代码本地缓存?"
									OnConfirm="(e) => codeEditBoxModal.ClearCacheCodeData(context)"
									OkText="Yes"
									CancelText="No">
							<Button Icon="@IconType.Outline.Clear" Shape="@ButtonShape.Circle" Danger></Button>
						</Popconfirm>
					</SpaceItem>
				</Space>
			</ActionColumn>
		</ColumnDefinitions>
		<ExpandTemplate Context="rowData">
			<Table Class="childTable" TItem="SysSageKingMessageAttribute" DataSource="rowData.Data.Children" Loading="rowData.Data.Children==null" Size=@TableSize.Small EnableVirtualization PageSize="10" ScrollY="200px" PaginationPosition="bottomCenter"
				   @bind-SelectedRows="@selectedRowsAttr" RowKey="a=>a.Id.ToString()" OnRowClick="OnRowAttrClick" Resizable Bordered>
				<TitleTemplate>
					<Space>
						<SpaceItem>
							<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.AppstoreAdd" OnClick="(e)=>skMessageAttFrmModal.MeCrud.ShowAdd(rowData.Data,false)">新增属性</Button>
						</SpaceItem>

						<SpaceItem>
							<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Import" OnClick="(e)=>skMessageAttImportFrmModal.MeCrud.ShowAdd(rowData.Data,false)">快速导入</Button>
						</SpaceItem>
					</Space>

				</TitleTemplate>
				<ColumnDefinitions>
					<Selection Key="@rowData.Data.Id.ToString()" Type="@selectionType"></Selection>
					<PropertyColumn Property="c=>c.Name" Title="属性名称" Sortable="true" Filterable />
					<PropertyColumn Property="c=>c.Type" Title="类型" Sortable="true" Align="ColumnAlign.Center" Filterable>
						<Text>@context.Type.GetDescription(true)</Text>
					</PropertyColumn>
					<PropertyColumn Property="c=>c.Status" Title="Status" Sortable="true" Align="ColumnAlign.Center" Filterable>
						<Switch @bind-Value="@context.Status" OnClick="()=>skMessageAttFrmModal.EditOnStatusSwitch(context)" CheckedChildren="开" UnCheckedChildren="关"></Switch>
					</PropertyColumn>
					<PropertyColumn Property="c=>c.Description" Title="描述信息" Ellipsis />
					<PropertyColumn Property="c=>c.Id" Title="Id" Sortable="true" Filterable />
					<PropertyColumn Property="c=>c.MessageId" Title="MessageId"></PropertyColumn>
					<PropertyColumn Title="时间相关" Property="c=>c.CreateUserName" Align="ColumnAlign.Center">
						<Popover ContentTemplate="@baseRender.GetDetails(context)" Title="时间相关">
							<Button Icon="@IconType.Outline.OrderedList" Shape="@ButtonShape.Circle" />
						</Popover>
					</PropertyColumn>
					<ActionColumn Title="Action" Fixed="ColumnFixPlacement.Right">
						<Space>
							<SpaceItem>
								<Tooltip Title="@IconType.Outline.Edit">
									<Button OnClick="
                                        (e)=>
                                    {
                                    skMessageAttFrmModal.ParentName=rowData.Data.Name;
                                    skMessageAttFrmModal.MeCrud.ShowEdit(context);
                                    }"
											Shape="@ButtonShape.Circle" Icon="@IconType.Outline.Edit" />
								</Tooltip>
							</SpaceItem>
							<SpaceItem>
								<Popconfirm Title="确认删除?"
											OnConfirm="() => skMessageAttFrmModal.DeleteData(context,rowData.Data)"
											OkText="Yes"
											CancelText="No">
									<Button Icon="@IconType.Outline.Delete" Shape="@ButtonShape.Circle" Danger></Button>
								</Popconfirm>

							</SpaceItem>
						</Space>
					</ActionColumn>
				</ColumnDefinitions>
				<PaginationTemplate>
					<Pagination Class="@(context.PaginationClass + " my-custom-pagination")"
								Total="context.Total"
								ShowTotal="baseRender.showTotal"
								PageSize="context.PageSize"
								Current="context.PageIndex"
								ShowSizeChanger
								OnChange="context.HandlePageChange" />
				</PaginationTemplate>
			</Table>
		</ExpandTemplate>


		<PaginationTemplate>
			<Pagination ShowTotal="baseRender.showTotal" Class="@(context.PaginationClass + " my-custom-pagination")"
						Total="pageData.Total"
						PageSize="pageData.PageSize"
						Current="pageData.Page"
						ShowSizeChanger
						ShowQuickJumper
						OnChange="OnSearch" />
		</PaginationTemplate>
	</Table>

	<Modal Title="@skMessageMainFrmModal.Title"
		   @bind-Visible="@skMessageMainFrmModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="skMessageMainFrmModal.HandleOk" ConfirmLoading="skMessageMainFrmModal.Loading" OkText="skMessageMainFrmModal.OkTitle" CancelText="skMessageMainFrmModal.CancelText">

		@skMessageMainFrmModal.ModalTemplate
	</Modal>

	<Modal Title="@skMessageAttFrmModal.Title" Class="modelDefault"
		   @bind-Visible="@skMessageAttFrmModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="skMessageAttFrmModal.HandleOk" ConfirmLoading="skMessageAttFrmModal.Loading" OkText="skMessageAttFrmModal.OkTitle" CancelText="skMessageAttFrmModal.CancelText">

		@skMessageAttFrmModal.ModalTemplate
	</Modal>

	<Modal Title="@skMessageAttImportFrmModal.Title" Class="modelDefault"
		   @bind-Visible="@skMessageAttImportFrmModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="skMessageAttImportFrmModal.HandleOk" ConfirmLoading="skMessageAttImportFrmModal.Loading" OkText="skMessageAttImportFrmModal.OkTitle" CancelText="skMessageAttImportFrmModal.CancelText">

		@skMessageAttImportFrmModal.ModalTemplate
	</Modal>

	<Modal Title="@skImportFrmDBModal.Title" Class="modelDefault" MaxBodyHeight="@("77vh")" Resizable Width="777"
		   @bind-Visible="@skImportFrmDBModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="skImportFrmDBModal.HandleOk" ConfirmLoading="skImportFrmDBModal.Loading" OkText="skImportFrmDBModal.OkTitle" CancelText="skImportFrmDBModal.CancelText" OnCancel="skImportFrmDBModal.HandleClose">
		  
		@skImportFrmDBModal.ModalTemplate
	</Modal>

	<Modal Title="@codeEditBoxModal.Title" Class="modelDefault" MaxBodyHeight="@("65vh")" 
		   @bind-Visible="@codeEditBoxModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="codeEditBoxModal.HandleOk" ConfirmLoading="codeEditBoxModal.Loading" OkText="codeEditBoxModal.OkTitle" CancelText="codeEditBoxModal.CancelText">

		@codeEditBoxModal.ModalTemplate
	</Modal>

	<Modal Title="@skMessageFrmToSendModal.Title" Class="modelDefault" MaxBodyHeight="@("65vh")" Resizable=true Width="888"
		   @bind-Visible="@skMessageFrmToSendModal.Visible" Draggable="@(true)" Centered Closable="false"
		   OnOk="skMessageFrmToSendModal.HandleOk" ConfirmLoading="skMessageFrmToSendModal.Loading" OkText="skMessageFrmToSendModal.OkTitle" CancelText="skMessageFrmToSendModal.CancelText">

		@skMessageFrmToSendModal.ModalTemplate
	</Modal>
}

@code {

	bool loading;
	bool IsfirstRender = false;

	BaseRenderFragment baseRender;

	//table
	ITable table;
	bool tableLoading;
	SelectionType selectionType = SelectionType.Checkbox;
	bool isOnRowExpand = false;

	//search
	SysSageKingMessage searchModel;
	SysDictType SelectSearchModelType;

	PaginationEventArgs pageargs = new PaginationEventArgs(1, 10);
	PageBase<SysSageKingMessage> pageData;

	IEnumerable<SysSageKingMessage> selectedRows;
	IEnumerable<SysSageKingMessageAttribute> selectedRowsAttr;

	//select data
	SysDictType SelectDataType;

	#region init
	#region menu

	public IMenuTab<SysMenu, long> MeTab { get { return this; } }

	public IBaseServiceCache<SysMenu, long> MenuService
	{ get { return _sysMenuService; } }

	[SupplyParameterFromQuery(Name = "menuid")]
	public long menuid { get; set; }

	[Parameter]
	public string TabTitle { get; set; } = "消息结构定义";

	[Parameter]
	public string TabIcon { get; set; } = "home";

	public RenderFragment GetPageTitle() =>
	@<div>
		<Icon Type="@TabIcon" /> @TabTitle
	</div>
	;
	#endregion

	[CascadingParameter]
	public Error? Error { get; set; }

	protected override async Task OnInitializedAsync()
	{
		try
		{
			baseRender = new BaseRenderFragment();

			await InitSelectData();
			await InitSeachMain();
			await InitModal();
			await Refresh(false);
			await MeTab.InitTabTitle();

		}
		catch (Exception ex)
		{
			Error?.ProcessError(ex);
		}
	}

	async Task InitSeachMain()
	{
		searchModel = new SysSageKingMessage();
		SelectSearchModelType = await selectService.GetDetailCache(SysDictTypeConst.code_message_type);

	}

	async Task InitSelectData()
	{
		SelectDataType = await selectService.GetDetailCache(SysDictTypeConst.code_message_type);
	}

	string? GetTypeDesc(int type)
	{
		return SelectDataType?.Children?.FirstOrDefault(a => a.ValueInt == type)?.CodeValue;
	}

	async Task InitModal()
	{
		initSageKingMessageFormEditModal();
		InitSysSageKingMessageEditModal();
		InitSysSageKingMessageAttributeEditModal();
		InitImportDataAttPageModal();
		InitImportFromDBAttPageModal();
		InitCodeEditBoxModal();

		await Task.CompletedTask;
	}

	#endregion

	async Task Refresh(bool notice = true)
	{
		await OnSearch(pageargs);
		if (isOnRowExpand)
		{
			table?.CollapseAll();
			isOnRowExpand = false;
		}
		if (notice)
		{
			_ = _message.SuccessAsync("刷新成功!");
		}
	}

	void SearchModelReSet()
	{
		searchModel = new SysSageKingMessage();
	}

	public async Task OnSearch(PaginationEventArgs args)
	{
		tableLoading = true;
		pageargs.Page = args.Page;
		pageargs.PageSize = args.PageSize;

		var page = new PageBaseInput() { Page = pageargs.Page, PageSize = pageargs.PageSize };

		var whereIf = new List<(bool, Expression<Func<SysSageKingMessage, bool>>)>();

		Expression<Func<SysSageKingMessage, bool>> whereIffunc1 = a => a.Name.Contains(searchModel.Name);
		Expression<Func<SysSageKingMessage, bool>> whereIffunc2 = a => a.Type == searchModel.Type;

		whereIf.Add((searchModel.Name.IsNotNullOrWhiteSpace(), whereIffunc1));
		whereIf.Add((searchModel.Type > 0, whereIffunc2));

		pageData = await dataService.GetPage(page, whereIf, a => a.Id, false);

		InitPageData();

		tableLoading = false;

		StateHasChanged();
	}

	void InitPageData()
	{

		skImportFrmDBModal.PageData = pageData;
		skMessageAttFrmModal.PageData = pageData;
		skMessageMainFrmModal.PageData = pageData;
		skMessageAttImportFrmModal.PageData = pageData;
	}

	public async Task<List<SysSageKingMessageAttribute>> QueryChildList(long ParentId)
	{
		Expression<Func<SysSageKingMessageAttribute, bool>> func = a => a.MessageId == ParentId;
		Expression<Func<SysSageKingMessageAttribute, object>> orderbyfunc = a => a.Id;

		return await dataDetailService.GetList(func, orderbyfunc, false);
	}

	private async void OnRowClick(RowData<SysSageKingMessage> data)
	{
		var row = data.Data;
		await QueryChildList(row.Id);
	}

	private void OnRowAttrClick(RowData<SysSageKingMessageAttribute> data)
	{
		var row = data.Data;
	}

	private async void OnRowExpand(RowData<SysSageKingMessage> data)
	{
		isOnRowExpand = true;
		data.Data.Children = await QueryChildList(data.Data.Id);
		skMessageAttImportFrmModal.attrNames = data.Data.Children.Select(a => a.Name).ToList();
		StateHasChanged();
	}

	void OnChange(QueryModel<SysSageKingMessage> query)
	{
		var dd = query;
	}


	void Message(string msg = "查询成功")
	{
		_ = _message.SuccessAsync(msg);
	}
}

@code {
	//主表
	[Inject]
	SysSageKingMessageEditModal skMessageMainFrmModal { get; set; }

	void InitSysSageKingMessageEditModal()
	{
		skMessageMainFrmModal.Error = Error;

		skMessageMainFrmModal.TabTitle = TabTitle;

		skMessageMainFrmModal.ModalTemplate = @<SysSageKingMessageEdit @ref=@skMessageMainFrmModal.Component Title="@skMessageMainFrmModal.Title" model="@skMessageMainFrmModal.Model"></SysSageKingMessageEdit>;

		skMessageMainFrmModal.RefreshFunc = Refresh;
		skMessageMainFrmModal.ResetDataAction = () =>
		{
			table?.ResetData();
		};
		skMessageMainFrmModal.StateHasChanged = StateHasChanged;
	}
}

@code {
	//明细表
	[Inject]
	SysSageKingMessageAttributeEditModal skMessageAttFrmModal { get; set; }

	void InitSysSageKingMessageAttributeEditModal()
	{
		skMessageAttFrmModal.Error = Error;

		skMessageAttFrmModal.TabTitle = TabTitle + "->消息属性";

		skMessageAttFrmModal.ModalTemplate = @<SysSageKingMessageAttributeEdit @ref="@skMessageAttFrmModal.Component" model="@skMessageAttFrmModal.Model"></SysSageKingMessageAttributeEdit>;

		skMessageAttFrmModal.QueryChildListFunc = QueryChildList;
		skMessageAttFrmModal.StateHasChanged = StateHasChanged;
	}

}

@code {

	//明细表 导入
	[Inject]
	ImportDataAttPageModal skMessageAttImportFrmModal { get; set; }

	void InitImportDataAttPageModal()
	{
		skMessageAttImportFrmModal.Error = Error;

		skMessageAttImportFrmModal.TabTitle = TabTitle + "->消息属性->快速导入";

		skMessageAttImportFrmModal.ModalTemplate = @<ImportDataAttPage @ref=@skMessageAttImportFrmModal.Component ParentId="@skMessageAttImportFrmModal.messageId" AttrNames="@skMessageAttImportFrmModal.attrNames"></ImportDataAttPage>;

		skMessageAttImportFrmModal.QueryChildListFunc = QueryChildList;
		skMessageAttImportFrmModal.StateHasChanged = StateHasChanged;
	}
}

@code {

	//消息 从数据库表 导入
	[Inject]
	ImportFromDBAttPageModal skImportFrmDBModal { get; set; }

	void InitImportFromDBAttPageModal()
	{
		skImportFrmDBModal.Error = Error;

		skImportFrmDBModal.TabTitle = TabTitle + "->消息结构->快速导入(数据库)";

		skImportFrmDBModal.ModalTemplate = @<ImportFromDBAttPage @ref="@skImportFrmDBModal.Component" model="@skImportFrmDBModal.Model"></ImportFromDBAttPage>;

		skImportFrmDBModal.RefreshFunc = Refresh;
		skImportFrmDBModal.StateHasChanged = StateHasChanged;
	}
}

@code {
	//消息操作，用于发送，及推送
	[Inject]
	SageKingMessageFormEditModal<SysSageKingMessage, SysSageKingMessageAttribute> skMessageFrmToSendModal { get; set; }

	void initSageKingMessageFormEditModal()
	{
		skMessageFrmToSendModal.Error = Error;

		skMessageFrmToSendModal.TabTitle = TabTitle;

		skMessageFrmToSendModal.ModalTemplate = @<SageKingMessageFormEdit @ref="@skMessageFrmToSendModal.Component" model="@skMessageFrmToSendModal.Model"></SageKingMessageFormEdit>;

		skMessageFrmToSendModal.GetTypeDescFunc = GetTypeDesc;
		skMessageFrmToSendModal.QueryChildListFunc = QueryChildList;

		skMessageFrmToSendModal.InitMessageInstance = dataInstanceService.InitData<SysSageKingMessage, SysSageKingMessageAttribute>;
	}

	//实例化当前消息
}

@code {

	//代码生成显示
	[Inject]
	CodeEditBoxModal<SysSageKingMessage, SysSageKingMessageAttribute> codeEditBoxModal { get; set; }

	void InitCodeEditBoxModal()
	{
		codeEditBoxModal.Error = Error;

		codeEditBoxModal.TabTitle = TabTitle;

		codeEditBoxModal.ModalTemplate = @<CodeEditBox markdownValue="@codeEditBoxModal.Model" isShow="true" @ref="@codeEditBoxModal.Component"></CodeEditBox>;

		codeEditBoxModal.GetTypeDescFunc = GetTypeDesc;
		codeEditBoxModal.QueryChildListFunc = QueryChildList;
		codeEditBoxModal.StateHasChanged = StateHasChanged;
	}
}

